/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session04;

import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
 *
 * @author sinhnx <sinhnx@fpt.aptech.ac.vn>
 */
public class EncrypDecryptDemo {

    public static void main(String[] args) {
        try {
            String msg = "Hello World";

            KeyGenerator key = KeyGenerator.getInstance("DES");
            SecretKey sKey = key.generateKey();

            System.out.println("KEY: " + sKey);

            Cipher ci = Cipher.getInstance("DES/ECB/PKCS5Padding");

            //Encrypt
            ci.init(Cipher.ENCRYPT_MODE, sKey);

            //encrypt data store to e
            byte[] e = ci.doFinal(msg.getBytes());
            System.out.println("encrypted:" + new String(e));

            //Decrypt
            ci.init(Cipher.DECRYPT_MODE, sKey);

            //Decrypt and transform to text to show to screen
            System.out.println("decrypted:" + new String(ci.doFinal(e)));
        } catch (Exception ex) {
            Logger.getLogger(EncrypDecryptDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
